﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SecureCommander.Core.UserManagement;
using SecureCommander.Helper;
using System.Text.RegularExpressions;
using SecureCommander.Core.SecurityManager;

namespace SecureCommander.GUI
{
    /// <summary>
    /// Interaction logic for FormRegisterUser.xaml
    /// </summary>
    public partial class FormRegisterUser : Window
    {
        public List<UserInfo> Users { get; set; }
        public UserInfo User { get; set; }
        public bool IsUpdate { get; set; }
        public bool IsImport { get; set; }

        public FormRegisterUser()
        {
            IsUpdate = false;
            IsImport = false;
            InitializeComponent();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckDataInput())
            {
                return;
            }

            if (User == null)
            {
                User = new UserInfo();
            }
            User.Mail = txtEmail.Text;
            User.Name = txtFullName.Text;
            if (!IsImport)
            {
                HashAlg hash = new HashAlg();
                User.Salt = hash.CreateSalt();
                User.Hash = hash.CreateHashFromPass_Salt(txtPassword.Password, User.Salt);
                RijndaelAlgorithm rij = new RijndaelAlgorithm();
                RSAAlgorithm rsa = new RSAAlgorithm((int)sliderKeySize.Value * 8);
                User.Publickey = rsa.StrPublickey;
                User.Privatekey = rij.Encrypt(rsa.StrPrivatekey, txtPassword.Password);
            }

            DialogResult = true;
            e.Handled = true;
            this.Close();
        }

        private bool CheckDataInput()
        {
            if (txtFullName.Text == "" || (!IsImport && txtPassword.Password == "") || (!IsImport && txtEmail.Text == ""))
            {
                FileHelper.ShowMessage("Please ! Fill all required informations", MessageBoxImage.Warning);
                return false;
            }

            //check format email 
            string EmailPattern = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            Regex emailRegex = new Regex(EmailPattern);
            if (!emailRegex.IsMatch(txtEmail.Text))
            {
                FileHelper.ShowMessage("Format email invalid", MessageBoxImage.Warning);
                return false;
            }

            if (!IsUpdate)
            {
                foreach (UserInfo u in Users)
                {
                    if (u.Mail == txtEmail.Text)
                    {
                        FileHelper.ShowMessage("Email already exists! Please try another one.", MessageBoxImage.Warning);
                        return false;
                    }
                }
            }

            if (txtPassword.Password != txtRePassword.Password)
            {
                FileHelper.ShowMessage("Passphrase not match", MessageBoxImage.Warning);
                return false;
            }
            if (sliderKeySize.Value < 64 || sliderKeySize.Value > 128)
            {
                FileHelper.ShowMessage("Keysize invalid (Keysize must be  between 64 byte and 128 byte)", MessageBoxImage.Warning);
                return false;
            }
            return true;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsUpdate)
            {
                Title = "Update User";
                txtEmail.IsEnabled = false;
            }

            if (IsImport)
            {
                txtPassword.ToolTip = txtRePassword.ToolTip = "Do not type anything to use import password";
                //txtPassword.Password = txtRePassword.Password = "DUMMY_PASSWORD";
                //txtPassword.IsEnabled = txtRePassword.IsEnabled = false;
            }

            if (User != null)
            {
                txtEmail.Text = User.Mail;
                txtFullName.Text = User.Name;
            }
            txtEmail.Focus();
        }
    }
}
